var express = require("express");
var router = express.Router();

const axios = require("axios");

const { generateToken, verifyToken } = require("../utils/index");

let userList = [];

/* GET users listing. */
router.post("/login", function (req, res, next) {
  if (req.body.code) {
    axios
      .get("https://api.weixin.qq.com/sns/jscode2session", {
        params: {
          appid: "wx034d9b8d34d80819",
          secret: "97ec4f5289f91b5c639c8a6a7ce9beba",
          js_code: req.body.code,
          grant_type: "authorization_code",
        },
      })
      .then((response) => {
        const { openid, session_key } = response.data;

        const token = generateToken(openid, session_key);

        const result = userList.some((item) => item.openid === openid);
        if (!result) {
          userList.push({
            openid,
            nickName: "用户" + openid.substring(0, 5),
            avatarUrl:
              "https://mmbiz.qpic.cn/mmbiz/icTdbqWNOwNRna42FI242Lcia07jQodd2FJGIYQfG0LAJGFxM4FbnQP6yfMxBgJ0F3YRqJCJ1aPAK2dQagdusBZg/0",
            focusList: [],
          });
        }

        res.json({
          success: true,
          msg: "登录成功",
          token: token,
        });
      });
  } else {
    res.json({
      success: false,
      msg: "缺少登录凭证",
    });
  }
});

router.get("/info", (req, res, next) => {
  const token = req.headers["authorization"];
  verifyToken(token)
    .then((response) => {
      const { openid } = response;

      const user = userList.find((item) => item.openid === openid);
      res.json({
        success: true,
        nickName: user.nickName,
        avatarUrl: user.avatarUrl,
      });
    })
    .catch((err) => {
      if (err.message) {
        res.json({
          success: false,
          msg: "token无效",
        });
      }
    });
});

router.get("/edit", (req, res, next) => {
  const token = req.headers["authorization"];
  const { nickName, avatarUrl } = req.query;

  if (nickName && avatarUrl) {
    verifyToken(token)
      .then((response) => {
        const { openid } = response;

        userList.forEach((item) => {
          if (item.openid === openid) {
            item.nickName = nickName;
            item.avatarUrl = avatarUrl;
          }
        });
        res.json({
          success: true,
          msg: "修改成功",
        });
      })
      .catch((err) => {
        if (err.message) {
          res.json({
            success: false,
            msg: "token无效",
          });
        }
      });
  } else {
    res.json({
      success: false,
      msg: "参数错误",
    });
  }
});

router.get("/getdata", (req, res, next) => {
  const token = req.headers["authorization"];

  verifyToken(token)
    .then((response) => {
      res.json({
        a: 4,
      });
    })
    .catch((err) => {
      console.log(111);

      if (err.message) {
        res.json({
          success: false,
          msg: "token无效",
        });
      }
    });
});

module.exports = router;
